package com.mdp.workflow.bus.listener.global;

import com.mdp.core.SpringUtils;
import com.mdp.micro.client.CallBizService;
import com.mdp.workflow.cfg.FlowableListenerConfig;
import com.mdp.workflow.client.service.FlowMsgServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 任务节点前置监听处理类,由于启动后马上进入第一个审批节点，如果第一个审批节点创建不成功，会导致整个流程启动不成功，而此事件是在第一个任务节点创建前执行，因此涉及事务性的远程调用不能在此事件中执行。
 * 拿不到变量，此类没什么用,启动事件放在  ExecutionServiceImpl.start进行推送
 * @author: chenyc
 * @create: 2019-05-04 20:51
 **/
@Component
public class ProcessStartedListener implements FlowableEventListener {
	
	Log log=LogFactory.getLog(ProcessStartedListener.class);

	@Value(value = "${mdp.form.data-approva-uri:/lcode/formData/processApprova}")
	String formDataApprovaUri="";

	@Autowired
	CallBizService callBizService;

	@Autowired
	FlowMsgServiceImpl pushMsgService;

	 
	 public DelegateExecution getExecution(String executionId) {
	        if (executionId != null) {
	            CommandContext commandContext = CommandContextUtil.getCommandContext();
	            if (commandContext != null) {
	                return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
	            }
	        }
	        return null;
	    }
    @Override
    public void onEvent(FlowableEvent event) {
		if(FlowableListenerConfig.PROCESS_STARTED.equals(event.getType().name())) {



			String formId="";
			FlowableEntityEventImpl exec=((FlowableEntityEventImpl) event);
			formId=(String) exec.getExecution().getVariable("formId");

			//调用其它远程服务
			ExecutionEntityImpl exeEntity = (ExecutionEntityImpl) exec.getEntity();
			//如果有上送restUrl，回调restUrl推送审核数据
			String restUrl=(String) exeEntity.getVariable("restUrl");
			ProcessInstance processInstance = exeEntity.getProcessInstance();
			String mainTitle=processInstance.getName();
			String startUserid=exeEntity.getStartUserId();
			if(!StringUtils.isEmpty(restUrl)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();

				///processInstance.get
				String bizKey=processInstance.getBusinessKey();
				String processInstanceId=processInstance.getProcessInstanceId();
				Map<String,Object> flowVars=exeEntity.getVariables();
				String actId=exeEntity.getCurrentActivityId();
				String taskName=exeEntity.getCurrentActivityName();
				String branchId=exeEntity.getTenantId();
				String eventName=event.getType().name();
				paramMap.putAll(flowVars);
				paramMap.put("procInstId", processInstanceId);
				paramMap.put("startUserid", startUserid);
				paramMap.put("mainTitle", mainTitle);
				paramMap.put("assignee", "");
				paramMap.put("actId", actId);
				paramMap.put("taskName", taskName);
				paramMap.put("flowBranchId", branchId);
				paramMap.put("bizKey", bizKey);
				paramMap.put("eventName", eventName);
				paramMap.put("modelKey", exeEntity.getProcessDefinitionKey());

				if(!StringUtils.isEmpty(formId)) {
					paramMap.put("formId", formId);
					if(restUrl.indexOf(formDataApprovaUri)>=0) {
						callBizService.postForTips(restUrl, paramMap);
					}else {
						callBizService.postForTips(formDataApprovaUri, paramMap);
						callBizService.postForTips(restUrl, paramMap);
					}

				}else {
					callBizService.postForTips(restUrl, paramMap);
				}
			}
			TaskService ts=SpringUtils.getBean(TaskService.class);
			ts.addComment(null, processInstance.getProcessInstanceId(), "流程启动");
			pushMsgService.pushMsg(startUserid, "您已发起流程【"+mainTitle+"】");
		}
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}